#!/usr/bin/python -O

import sys, os, socket
import time
import json

import qpid.exceptions

from amqp_old import RoutingKey, Receiver
from protomsg import GpbMessage

if len(sys.argv) < 2:
    sys.argv.extend(['--ip=sq169.houston.hp.com',  '--port=61271',
                     '--binding-key=#.query_sql_text',
                     '--binding-key=#.query_end_stats',
                     '--output-file=sq169.sql.log',
                     '--proto-src=' + os.environ['HOME'] + '/publications'])
    
# -- main start here --
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-i', '--ip', dest = 'brokerIp',
      action = 'store', default = '127.0.0.1',
      help = 'ip address of the broker to publish, default [%default]')
parser.add_option('-p', '--port', dest = 'brokerPort',
      action = 'store', type = int, default = 5672,
      help = 'port of the broker to subscribe, default [%default]')
parser.add_option('--proto-src', dest ='protoSrc',
      action = 'store', default = os.environ['HOME'] + '/publications',
      help = 'directory to store subscribe, default [%default]')
parser.add_option('-o', '--output-file', dest ='out',
      action = 'store', default = sys.stdout,
      help = 'file to dump message text, default [stdout]')
parser.add_option('-k', '--binding-key', dest = 'bindingKeys',
      action = 'append')
parser.add_option('-q', '--queue-name', dest ='queueName',
      action = 'store', default = 'get_queue_%d' % os.getpid(),
      help = 'queue name, default [%default]')

(opts, args) = parser.parse_args()

if __debug__: print opts

if opts.bindingKeys is None:
    opts.bindingKeys = ['#']

try:
    receiver = Receiver(opts.brokerIp, opts.brokerPort)
    receiver.setup(opts.bindingKeys, opts.queueName)

    if opts.out == sys.stdout:
        output = sys.stdout
    else:
        output = open(opts.out, 'w')

    try:
        while True:
            message = receiver.fetch(timeout=10000)

            for header in message.headers:
                routingKeyStr = None
                try:
                    routingKeyStr = getattr(header, 'routing_key')
                except AttributeError, e:
                    continue

                if routingKeyStr:
                    print '{Message : %s}' % routingKeyStr
                    if output != sys.stdout:
                        output.write('{"Message" : "%s"}\n' % routingKeyStr)

                    if __debug__:
                        rKey = RoutingKey(routingKeyStr)

                        pMsg = GpbMessage(opts.protoSrc,
                                        rKey.package, rKey.publication)
                        pMsg.loads(message.body)

                        try:
                            info_time_utc = pMsg.field_value(
                                    'header.info_generation_time_ts_utc')
                        except:
                            try:
                                info_time_utc = pMsg.field_value(
                                    'header.header.info_generation_time_ts_utc')
                            except:
                                try:
                                    info_time_utc = pMsg.field_value(
                                        'checkinfo.header.header.info_generation_time_ts_utc')
                                except:
                                    info_time_utc = pMsg.field_value(
                                        'subjectinfo.header.header.info_generation_time_ts_utc')

                        def format_time(time_):
                            return time.strftime('%Y-%m-%d %H:%M:%S',
                                time.localtime(time_))

                        print 'Sent at', format_time(info_time_utc / 1000000),
                        print 'Got at', format_time(time.time())

                        outTpa = pMsg.dumptabs()
                        outJson = pMsg.dumpjson()

                        output.write('%s\n' % outTpa)
                        json.dump(outJson, output)
                        output.write('\n%s\n' % pMsg)
                        output.flush()

                    break


    except qpid.exceptions.Closed:
        print 'Qpid connection closed, exiting...'

    except qpid.exceptions.Timeout:
        print 'Broker timedout, exit...'

    except qpid.exceptions.VersionError:
        print 'Incompatible broker version, exiting...'

    except KeyboardInterrupt:
        print 'Control-C pressed, exiting...'

    finally:
        if output != sys.stdout: output.close()

except socket.error, e:
    print 'Could not connect to server, exiting...'

